<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Model\data\CurrentShopData;
use App\Model\DeliveryTpl;
use App\Service\DeliveryTplService;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Rule;

class DeliveryController extends AbstractController
{

    /**
     * @Inject
     * @var DeliveryTplService
     * */
    private $deliveryTplService;

    public function list()
    {
        $params = $this->request->all();

        $list = $this->deliveryTplService->get_list($params);

        $list =$list?$list->get()->toArray():[];

        $shop_info = CurrentShopData::getData();
        if ($shop_info) {
            $shop_id = $shop_info->id;
        }
        $high = $this->deliveryTplService->order_tpl(2,intval($shop_info->id));
        $low = $this->deliveryTplService->order_tpl(3,intval($shop_info->id));
        $init_tpl= $this->deliveryTplService->get_init_tpl(intval($shop_info->id));
        $return = [
            'list'=>$list,
            'order_high'=>$high,
            'order_low'=>$low,
            'init_tpl'=>$init_tpl,
        ];
        return $this->jsonResponse->success($return,'邮费模板');
    }


    public function detail()
    {
        $id = $this->request->input('id');
        return $this->jsonResponse->success($this->deliveryTplService->info(intval($id)),'商品邮费模板');
    }

    public function get_order_tpl()
    {
        $shop_info = CurrentShopData::getData();

        $type = $this->request->input('type','');
        if(!in_array($type,[2,3])){
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'必填高低优先级,2高优先级  3低优先级');
        }
        return $this->jsonResponse->success($this->deliveryTplService->order_tpl(intval($type),$shop_info->id),'订单邮费模板');
    }

    public function del()
    {
        $id = $this->request->input('id');
        $shop_info =  CurrentShopData::getData();
        $shop_info = $shop_info->toArray()?$shop_info->toArray():[];
        $this->validation(['id'=>$id],
            [
                "id"=>[
                    'required',
                    'string',
                    'max:50',
                    Rule::exists('fly_delivery_tpl')->where('shop_id',$shop_info['id'])->whereNull('deleted_at'),
                ],
            ]
        );
        Db::beginTransaction();
        try {
            Db::commit();
            return $this->jsonResponse->success($this->deliveryTplService->delete_tpl(intval($id),$this->getAdminId()),'删除成功');
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'删除失败.'.$exception->getMessage());
        }

    }

    public function open_close()
    {
        $params = $this->request->inputs(['use_type','is_use']);
        $shop_info =  CurrentShopData::getData();
        $shop_info = $shop_info?$shop_info->toArray():[];
        $this->validation($params,
            [
                "use_type"=>[
                    'required',
                    'integer',
                    'between:1,3',
                    Rule::exists('fly_delivery_tpl','use_type')
                        ->where('shop_id',$shop_info['id']),
                ],
                "is_use"=>[
                    'required',
                    'boolean',
                ],
            ]
        );
        Db::beginTransaction();
        try {
            Db::commit();
            return $this->jsonResponse->success($this->deliveryTplService->open_close(intval($params['use_type']),intval($params['is_use'])),'修改成功');
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败.'.$exception->getMessage());
        }

    }
    public function add(){
        $params = $this->request->all();
        $shop_info =  CurrentShopData::getData();
        $shop_info = $shop_info?$shop_info->toArray():[];
        $validator  = $this->validationFactory->make($params,
        [
            "use_type"=>[
                'required',
                'integer',
                'between:1,3',
            ],
            "rule_type"=>[
                'between:1,4',
                Rule::requiredIf($params['is_free']==0&&$params['use_type']==1),
            ],
            "tpl_name"=>[
                'required',
                'string',
                'max:50',
                Rule::unique('fly_delivery_tpl')->where('shop_id',$shop_info['id']),
            ],
            "is_free"=>'required|boolean',
            "is_other_free"=>[
                'boolean',
                Rule::requiredIf($params['is_free']==0&&$params['use_type']==1),
            ],
            "other_free_set"=>[
                'integer',
                Rule::requiredIf(isset($params['is_other_free'])&&$params['is_other_free']==1),
            ],
            "is_all_area"=>[
                'integer',
                'boolean',
                Rule::requiredIf($params['is_free']==0&&$params['use_type']==1),
            ],
//            "min_price_free"=>[
//                'numeric',
//                Rule::requiredIf($params['is_all_area']==1&&$params['use_type']!=1),
//            ],
            "rules"=>[
                'array',
                Rule::requiredIf($params['is_free']==0&&$params['is_all_area']==0),
            ],
            "rules.*.area_free"=>[
                'boolean',
                Rule::requiredIf($params['is_free']==0&&$params['is_all_area']==0),
            ],
            "rules.*.provinces"=>[
                'array',
                Rule::requiredIf($params['is_free']==0&&$params['is_all_area']==0),
            ],
        ]
        );

        if(isset($params['use_type'])){
            $validator->sometimes('use_type', [Rule::unique('fly_delivery_tpl','use_type')->where('shop_id',$shop_info['id'])],
                function($inputs) {
                    return $inputs->use_type != 1;
                });
        }
        if ($validator->fails()) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, $validator->errors()->first());
        }
        Db::beginTransaction();
        try {
            $admin_id =  parent::getAdminId();
            $params['created_at'] = date('Y-m-d H:i:s');
            $params['create_by'] = $admin_id;
            $tpl_id  = $this->deliveryTplService->add_tpl($params,$shop_info);
            if($tpl_id){
                Db::commit();
                return $this->jsonResponse->success([],'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败.'.$exception->getMessage());
        }
    }

    public function edit(){
        $params = $this->request->all();
        $shop_info =  CurrentShopData::getData();
        $shop_info = $shop_info?$shop_info->toArray():[];
        $validator  = $this->validationFactory->make($params,
            [
                "id"=>[
                    'required',
                    'string',
                    'max:50',
                    Rule::exists('fly_delivery_tpl')->where('shop_id',$shop_info['id']),
                ],
                "use_type"=>[
                    'required',
                    'integer',
                    'between:1,3',
                ],
                "rule_type"=>[
                    'between:1,4',
                    Rule::requiredIf($params['is_free']==0&&$params['use_type']==1),
                ],
                "tpl_name"=>[
                    'required',
                    'string',
                    'max:50',
                    Rule::unique('fly_delivery_tpl')->where('shop_id',$shop_info['id'])->ignore($params['id']),
                ],
                "is_free"=>'required|boolean',
                "is_other_free"=>[
                    'boolean',
                    Rule::requiredIf($params['is_free']==0&&$params['use_type']==1),
                ],
                "other_free_set"=>[
                    'integer',
                    Rule::requiredIf(isset($params['is_other_free'])&&$params['is_other_free']==1),
                ],
                "is_all_area"=>[
                    'boolean',
                    Rule::requiredIf($params['is_free']==0&&$params['use_type']==1),
                ],
//                "min_price_free"=>[
//                    'numeric',
//                    Rule::requiredIf($params['is_all_area']==1&&$params['use_type']!=1&&$params['rule_type']!=1),
//                ],
                "rules"=>[
                    'array',
                    Rule::requiredIf($params['is_free']==0&&$params['is_all_area']==0),
                ],
                "rules.*.area_free"=>[
                    'boolean',
                    Rule::requiredIf($params['is_free']==0&&$params['is_all_area']==0),
                ],
                "rules.*.provinces"=>[
                    'array',
                    Rule::requiredIf($params['is_free']==0&&$params['is_all_area']==0),
                ],
            ]
        );
        if(isset($params['use_type'])){
            $validator->sometimes('use_type', [
                Rule::unique('fly_delivery_tpl','use_type')
                ->where('shop_id',$shop_info['id'])
                ->where('use_type',$params['use_type'])
                ->ignore($params['id'])],
                function($inputs) {
                    return $inputs->use_type != 1;
                });
        }
        if ($validator->fails()) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, $validator->errors()->first());
        }
        try {
            $admin_id =  parent::getAdminId();
            $params['updated_at'] = date('Y-m-d H:i:s');
            $params['update_by'] = $admin_id;
            $tpl_id  = $this->deliveryTplService->edit_tpl($params,$shop_info);
            if($tpl_id){
                Db::commit();
                return $this->jsonResponse->success([],'修改成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败.'.$exception->getMessage());
        }
    }

}
